package com.ctvit.struts.action;

import com.ctvit.common.DateTimeUtil;
import com.ctvit.framework.struts2.ActionSupport;
import com.ctvit.framework.web.context.ContextHolder;
import com.ctvit.sms.platform.domain.*;
import com.ctvit.sms.platform.service.CustomMsgService;
import com.ctvit.sms.platform.service.SmsService;
import com.ctvit.struts.common.CommonFunc;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.*;


/**
 * Created by LoreYun on 2016/3/10.
 */
public class CustomMsgAction extends ActionSupport {
	private CustomMsgService customMsgService = ContextHolder.getBean(CustomMsgService.class);
	private SmsService smsService = ContextHolder.getBean(SmsService.class);
	private static Logger logger = Logger.getLogger(CustomMsgAction.class);

	private HashMap TFBJson;       //回馈
	private HashMap myGroupTDataJson;       //我的群组table数据
	private HashMap groupMemberTDataJson;       //群成员table数据
	private HashMap staffTDataJson;       //台内人员table数据
	private HashMap retrievePersonTDataJson;   //待发送人员table数据
	private HashMap addedOutPersonJson;    //添加的台外人员table数据

	//list
	private HashMap textListJson;      //文本消息记录
	private HashMap meetingListJson;      //文本消息记录

	public static char SUCCESS = '1';
	public static char ERROR = '0';
	public static char ALERT = '2';

	private static String RETURN_CMSGTFB = "customMsgTFB";


	//=======list========   start
	public String getTextList(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_userID = request.getParameter("userID");

		textListJson = customMsgService.getTextListTDataByUserId(str_userID);
		return "textList";
	}

	public String getMeetingList() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_userID = request.getParameter("userID");

		meetingListJson = customMsgService.getMeetingListTDataByUserId(str_userID);
		return "meetingList";
	}
	//=======list========   end


	//=======attach========   start
	public String doDelMeetingAttach() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_attachNo = request.getParameter("attachNo");
		String str_meetingPk = request.getParameter("meetingPk");

		logger.debug("Action:doDelAttach:str_attachNo:" + str_attachNo + " ,str_meetingPk:" + str_meetingPk);

		if (StringUtils.isEmpty(str_attachNo)) {
			setTFBContent(ERROR, "attachNo不能为空");
			return RETURN_CMSGTFB;
		} else if (customMsgService.checkCmsgMeetingIsExist(str_meetingPk) == false) {
			setTFBContent(ERROR, "会议主键不存在");
			return RETURN_CMSGTFB;
		}
		customMsgService.doDelAttach("t_cmsg_meeting", str_meetingPk, Long.valueOf(str_attachNo));
		setTFBContent(SUCCESS, "删除成功");

		return RETURN_CMSGTFB;
	}

	//=======attach========   end
	//=======send========   start
	public String doSaveCustomMeetingMsg() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_meetingPk = request.getParameter("meeting_pk");
		String str_userID = request.getParameter("userID");
		String str_msgType = request.getParameter("msgType");
		String str_retrieveList = request.getParameter("retrieveList");
		String str_title = request.getParameter("title");         //会议主题
		String str_date = request.getParameter("date");         //会议日期
		String str_startTime = request.getParameter("startTime");         //开始时间
		String str_endTime = request.getParameter("endTime");         //结束时间
		String str_address = request.getParameter("address");         //会议地点
		String str_participants = request.getParameter("participants");         //主要参与人
		String str_contactPerson = request.getParameter("contactPerson");         //会议联系人
		String str_contact = request.getParameter("contact");         //会议联系方式
		String str_desc = request.getParameter("desc");         //会议描述
		net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(str_retrieveList);

		logger.debug("Action:doSaveCustomMeetingMsg:str_userID:" + str_userID + " ,str_msgType:" + str_msgType
				+ " ,str_retrieveList:" + str_retrieveList + " ,str_title:" + str_title + " ,str_date:" + str_date + " ,str_startTime:" + str_startTime
				+ " ,str_endTime:" + str_endTime + " ,str_address:" + str_address + " ,str_participants:" + str_participants
				+ " ,str_contactPerson:" + str_contactPerson + " ,str_contact:" + str_contact + " ,str_desc:"
				+ str_desc + ",,,,,,,,str_meetingPk:" + str_meetingPk);

		if (StringUtils.isEmpty(str_userID)) {
			setTFBContent(ERROR, "用户Id不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_msgType)) {
			setTFBContent(ERROR, "消息类型不能为空");
			return RETURN_CMSGTFB;
		} else if (str_retrieveList == null) {
			setTFBContent(ERROR, "待发送人员不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_title)) {
			setTFBContent(ERROR, "会议主题不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_date)) {
			setTFBContent(ERROR, "会议日期不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_startTime)) {
			setTFBContent(ERROR, "开始时间不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_endTime)) {
			setTFBContent(ERROR, "结束时间不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_address)) {
			setTFBContent(ERROR, "会议地点不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_participants)) {
			setTFBContent(ERROR, "主要参与人不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_contactPerson)) {
			setTFBContent(ERROR, "会议联系人不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_contact)) {
			setTFBContent(ERROR, "会议联系方式不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_desc)) {
			setTFBContent(ERROR, "会议描述不能为空");
			return RETURN_CMSGTFB;
		} else if (jsonArray == null || jsonArray.isEmpty()) {
			setTFBContent(ERROR, "待发送人员不能为空");
			return RETURN_CMSGTFB;
		}

		if (StringUtils.equals(str_msgType, "meetingMsg")) {            //会议通知
			//先看时间传的对不对
			Date meetingDate;
			try {
				meetingDate = DateTimeUtil.parseDate(str_date);
			} catch (ParseException e) {
				e.printStackTrace();
				setTFBContent(ERROR, "时间格式不正确");
				return RETURN_CMSGTFB;
			}
			if (meetingDate == null) {
				setTFBContent(ERROR, "时间格式不正确");
				return RETURN_CMSGTFB;
			}

			//判断主键是否存在了
			CmsgMeeting oldCmsgMeeting = null;
			if (StringUtils.isNotEmpty(str_meetingPk)) {
				oldCmsgMeeting = customMsgService.getCmsgMeeting(Long.valueOf(str_meetingPk));
			}

			if (StringUtils.isNotEmpty(str_meetingPk) && oldCmsgMeeting == null) { //传了主键 但是主键没找到  那就是主键错误 或者误传主键了
				setTFBContent(ERROR, "主键未找到!");
				return RETURN_CMSGTFB;
			} else if (StringUtils.isNotEmpty(str_meetingPk) && oldCmsgMeeting != null) { //传了主键 找到条目之后 要进行更新
				//设置新值
				oldCmsgMeeting.setTitle(str_title);                                        //会议主题  差 插入之前，看看有没有需要过滤的词语
				oldCmsgMeeting.setDate(meetingDate);                                     //会议日期
				oldCmsgMeeting.setStartTime(str_startTime);                      //会议开始时间
				oldCmsgMeeting.setEndTime(str_endTime);                         //会议结束时间
				oldCmsgMeeting.setAddress(str_address);                          //会议地点
				oldCmsgMeeting.setParticipants(str_participants);              //主要参与人
				oldCmsgMeeting.setContactPerson(str_contactPerson);     //会议联系人
				oldCmsgMeeting.setContact(str_contact);                          //会议联系方式
				oldCmsgMeeting.setDesc(str_desc);                                //会议描述

				//更新
				int updateEfectCount = customMsgService.doUpdateCmsgMeeting(oldCmsgMeeting);
				//删除待发送人员 重新插
				customMsgService.doDelRetrieve("1", oldCmsgMeeting.getMessagePk());
				//再将主表的主键 作为外键 将待发送人员插入待发送表
				ArrayList<CmsgRetrieve> retrieveList = getRetrieveListByJsonArray(jsonArray, oldCmsgMeeting.getMessagePk(), 1l);
				if (retrieveList == null) {                                           //别插入空的
					setTFBContent(ERROR, "待发送人员不能为空");                      //TODO 差事物回滚
					return RETURN_CMSGTFB;
				}
				int biEfectCount = customMsgService.doBatchInsertRetrieve(retrieveList);
				if (biEfectCount < 1) {                                             //看下插进去没
					setTFBContent(ERROR, "待发送人员插入失败");                      //TODO 差事物回滚
					return RETURN_CMSGTFB;
				} else {
					HashMap successResult = new HashMap();
					successResult.put("msg", "保存成功");
					successResult.put("pk", oldCmsgMeeting.getMessagePk());

					setTFBContent(SUCCESS, successResult);
					//				customMsgService.doGeneCmsgText(cmsgText.getMessagePk());      //保存和提交分离出来
				}
			} else {  //没传主键 需要新建
				//先插消息主表
				CmsgMeeting cmsgMeeting = customMsgService.insertCmsgMeeting(str_userID,
						str_title, meetingDate, str_startTime, str_endTime, str_address, str_participants,
						str_contactPerson, str_contact, str_desc);
				//再将主表的主键 作为外键 将待发送人员插入待发送表
				ArrayList<CmsgRetrieve> retrieveList = getRetrieveListByJsonArray(jsonArray, cmsgMeeting.getMessagePk(), 1l);
				if (retrieveList == null) {                                           //别插入空的
					setTFBContent(ERROR, "待发送人员不能为空");                      //TODO 差事物回滚
					return RETURN_CMSGTFB;
				}
				int effectCount = customMsgService.doBatchInsertRetrieve(retrieveList);
				if (effectCount < 1) {                                             //看下插进去没
					setTFBContent(ERROR, "待发送人员插入失败");                      //TODO 差事物回滚
					return RETURN_CMSGTFB;
				} else {
					HashMap successResult = new HashMap();
					successResult.put("msg", "保存成功");
					successResult.put("pk", cmsgMeeting.getMessagePk());

					setTFBContent(SUCCESS, successResult);
					//				customMsgService.doGeneCmsgMeeting(cmsgMeeting.getMessagePk());           //保存和提交分离出来
				}
			}
		} else {
			setTFBContent(ERROR, "msgType错误");  //msgType错误
		}
		return RETURN_CMSGTFB;
	}

	public String doSaveCustomTextMsg() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_textPk = request.getParameter("text_pk");
		String str_userID = request.getParameter("userID");
		String str_msgType = request.getParameter("msgType");
		String str_retrieveList = request.getParameter("retrieveList");
		String str_msgContent = request.getParameter("msgContent");
		net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(str_retrieveList);

		logger.debug("Action:doSaveCustomTextMsg:str_userID:" + str_userID
				+ ",str_msgType:" + str_msgType + ",str_retrieveList:" + str_retrieveList
				+ ",str_msgContent:" + str_msgContent + ",,,,,,,,str_textPk:" + str_textPk);
		if (StringUtils.isEmpty(str_userID)) {
			setTFBContent(ERROR, "用户Id不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_msgType)) {
			setTFBContent(ERROR, "消息类型不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_msgContent)) {
			setTFBContent(ERROR, "消息内容不能为空");
			return RETURN_CMSGTFB;
		} else if (str_retrieveList == null) {
			setTFBContent(ERROR, "待发送人员不能为空");
			return RETURN_CMSGTFB;
		} else if (jsonArray == null || jsonArray.isEmpty()) {
			setTFBContent(ERROR, "待发送人员不能为空");
			return RETURN_CMSGTFB;
		}

		if (StringUtils.equals(str_msgType, "textMsg")) {            //文本消息
			//先判断主键是否存在了
			CmsgText oldCmsgText = null;
			if (StringUtils.isNotEmpty(str_textPk)) {
				oldCmsgText = customMsgService.getCmsgText(Long.valueOf(str_textPk));
			}

			if (StringUtils.isNotEmpty(str_textPk) && oldCmsgText == null) { //传了主键 但是主键没找到  那就是主键错误 或者误传主键了
				setTFBContent(ERROR, "主键未找到!");
				return RETURN_CMSGTFB;
			} else if (StringUtils.isNotEmpty(str_textPk) && oldCmsgText != null) { //传了主键 找到条目之后 要进行更新
				//设置新值
//				oldCmsgText.setTitle(str_msgContent);               //不插title了
				oldCmsgText.setContent(str_msgContent);
				//更新
				int updateEfectCount = customMsgService.doUpdateCmsgText(oldCmsgText);
				//删除待发送人员 重新插
				customMsgService.doDelRetrieve("0", oldCmsgText.getMessagePk());
				//再将主表的主键 作为外键 将待发送人员插入待发送表
				ArrayList<CmsgRetrieve> retrieveList = getRetrieveListByJsonArray(jsonArray, oldCmsgText.getMessagePk(), 0l);
				if (retrieveList == null) {                                           //别插入空的
					setTFBContent(ERROR, "待发送人员不能为空");                      //TODO 差事物回滚
					return RETURN_CMSGTFB;
				}
				int biEfectCount = customMsgService.doBatchInsertRetrieve(retrieveList);
				if (biEfectCount < 1) {                                             //看下插进去没
					setTFBContent(ERROR, "待发送人员插入失败");                      //TODO 差事物回滚
					return RETURN_CMSGTFB;
				} else {
					HashMap successResult = new HashMap();
					successResult.put("msg", "保存成功");
					successResult.put("pk", oldCmsgText.getMessagePk());

					setTFBContent(SUCCESS, successResult);
					//				customMsgService.doGeneCmsgText(cmsgText.getMessagePk());      //保存和提交分离出来
				}
			} else {  //没传主键 需要新建
				//先插消息主表
				CmsgText cmsgText = customMsgService.insertCmsgText(str_msgContent, str_userID);
				//再将主表的主键 作为外键 将待发送人员插入待发送表
				ArrayList<CmsgRetrieve> retrieveList = getRetrieveListByJsonArray(jsonArray, cmsgText.getMessagePk(), 0l);
				if (retrieveList == null) {                                           //别插入空的
					setTFBContent(ERROR, "待发送人员不能为空");                      //TODO 差事物回滚
					return RETURN_CMSGTFB;
				}
				int biEfectCount = customMsgService.doBatchInsertRetrieve(retrieveList);
				if (biEfectCount < 1) {                                             //看下插进去没
					setTFBContent(ERROR, "待发送人员插入失败");                      //TODO 差事物回滚
					return RETURN_CMSGTFB;
				} else {
					HashMap successResult = new HashMap();
					successResult.put("msg", "保存成功");
					successResult.put("pk", cmsgText.getMessagePk());

					setTFBContent(SUCCESS, successResult);
					//				customMsgService.doGeneCmsgText(cmsgText.getMessagePk());      //保存和提交分离出来
				}
			}
		} else {
			setTFBContent(ERROR, "msgType错误");  //msgType错误
		}
		return RETURN_CMSGTFB;
	}

	public String doSentCustomMsg() {            //正常来说 文本消息保存时直接发送
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_msgPk = request.getParameter("msgPk");
		String str_msgType = request.getParameter("msgType");

		if (StringUtils.isEmpty(str_msgPk)) {
			setTFBContent(ERROR, "主键不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_msgType)) {
			setTFBContent(ERROR, "类型不能为空");
			return RETURN_CMSGTFB;
		}

		boolean tfb;
		if (StringUtils.equals(str_msgType, "textMsg")) {
			tfb = customMsgService.doGeneCmsgText(Long.valueOf(str_msgPk));
		} else if (StringUtils.equals(str_msgType, "meetingMsg")) {
			tfb = customMsgService.doGeneCmsgMeeting(Long.valueOf(str_msgPk));
		} else {
			setTFBContent(ERROR, "类型不正确");
			return RETURN_CMSGTFB;
		}

		if (tfb == true) {      //成功
			setTFBContent(SUCCESS, "发送成功");
		} else {        //失败
			setTFBContent(ERROR, "发送失败，请联系系统管理员");
		}
		return RETURN_CMSGTFB;
	}

	/**
	 * @param jsonArray 前台传的待发送人员列表
	 * @param msgPk     消息的主键(会议消息和短信消息是存在两个表中的)
	 * @param msgType   消息的类型               0   文本消息
	 *                  1  会议
	 * @return
	 */
	private ArrayList<CmsgRetrieve> getRetrieveListByJsonArray(net.sf.json.JSONArray jsonArray, Long msgPk, Long msgType) {
		if (jsonArray == null || jsonArray.isEmpty()) {
			logger.debug("getRetrieveListByJsonArray:jsonArray为空");
			return null;
//		} else if (StringUtils.isEmpty(msgPk)) {
		} else if (msgPk <= 0) {
			logger.debug("getRetrieveListByJsonArray:msgPk为空");
			return null;
		}

		ArrayList<CmsgRetrieve> retrieveList = new ArrayList<CmsgRetrieve>();
		for (int i = 0; i < jsonArray.size(); i++) {
			net.sf.json.JSONObject retrieveObj = jsonArray.getJSONObject(i);
			String str_zPerno = String.valueOf(retrieveObj.get("zPerno"));
			String str_zGroupNo = String.valueOf(retrieveObj.get("zGroupNo"));
			if (StringUtils.isNotEmpty(str_zPerno)) {
				CmsgRetrieve retrieve = new CmsgRetrieve();

				retrieve.setMessagePk(msgPk);
				retrieve.setGetUsersId(str_zPerno);
				retrieve.setDeptId(customMsgService.getDeptIDByUserId(str_zPerno));
				retrieve.setType(msgType);
				retrieve.setGroupId(str_zGroupNo);
				retrieve.setCreateTimestamp(new Timestamp(GregorianCalendar.getInstance().getTimeInMillis()));
				retrieveList.add(retrieve);
			}
		}

		return retrieveList;
	}

	//=======send========   end
	//=======retrieve========   start
	public String getRetrievePersonJsonByGroupID() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String[] str_groupIDList = request.getParameterValues("myGroupIDList[]");
		List<CmsgGroup> groupIDList, groupList;

		logger.debug("Action:getRetrievePersonListByGroupID" + str_groupIDList);
		//判断是不是为空
		if (str_groupIDList == null) {
			setTFBContent(ERROR, "群组Id不能为空");
			return RETURN_CMSGTFB;
		}
		//string数组转换为CmsgGroup对象数组
		groupIDList = new ArrayList<CmsgGroup>();
		for (String groupID : str_groupIDList) {
			if (StringUtils.isNotEmpty(groupID)) {
				CmsgGroup cmsgGroup = new CmsgGroup();
				cmsgGroup.setGroupId(Long.parseLong(groupID));
				groupIDList.add(cmsgGroup);
			}
		}
		//检测group有效性 返回有效的group
		groupList = customMsgService.getCmsgGroupByGroupIDList(groupIDList);
		if (groupList == null || groupList.size() < 1) {
			setTFBContent(ERROR, "找不到群组");
			return RETURN_CMSGTFB;
		}
		retrievePersonTDataJson = customMsgService.getRetrievePersonTDataByGroupIDList(groupList);
		if (retrievePersonTDataJson == null) {
			setTFBContent(ALERT, "群组内没有人员");
		} else {
			setTFBContent(SUCCESS, retrievePersonTDataJson.get("rows"));
		}
		return RETURN_CMSGTFB;
	}

	//=======retrieve========   end
	//=======insideMember========   start
	public String getStaffList() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_staffNo = request.getParameter("staffNo");
		String str_staffName = request.getParameter("staffName");
		String str_staffDept = request.getParameter("staffDept");

		logger.debug("getStaffList:" + str_staffNo);
		logger.debug("getStaffList:" + str_staffName);
		logger.debug("getStaffList:" + str_staffDept);
		if (StringUtils.isNotEmpty(str_staffNo)) {
			staffTDataJson = customMsgService.getStaffTableData(str_staffNo, null, null);
			return "staffList";
		} else if (StringUtils.isNotEmpty(str_staffName)) {
			staffTDataJson = customMsgService.getStaffTableData(null, str_staffName, null);
			return "staffList";
		} else if (StringUtils.isNotEmpty(str_staffDept)) {
			staffTDataJson = customMsgService.getStaffTableData(null, null, str_staffDept);
			return "staffList";
		} else {
			setTFBContent(ERROR, "人员工号、人员名称、部门名称不能都为空");
			return RETURN_CMSGTFB;
		}
	}

	//=======insideMember========   end
	//=======groupMember========   start
	public String getAddedOutsidePerson() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_userID = request.getParameter("userID");
		if (StringUtils.isEmpty(str_userID)) {
			setTFBContent(ERROR, "用户ID不能为空");
			return RETURN_CMSGTFB;
		}
		addedOutPersonJson = customMsgService.getAddedOutPersonTableData(str_userID);

		return "addedOutPersonList";
	}

	public String getOutsidePerson() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_outName = request.getParameter("outName");
		String str_outPhNum = request.getParameter("outPhoneNumber");
		logger.debug(str_outName);
		logger.debug(str_outPhNum);

		if (StringUtils.isEmpty(str_outName)) {
			setTFBContent(ERROR, "人员姓名不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_outPhNum)) {
			setTFBContent(ERROR, "人员手机号不能为空");
			return RETURN_CMSGTFB;
		} else if (CommonFunc.isMobileValid(str_outPhNum) == false) {
			setTFBContent(ERROR, "手机号格式不正确");
			return RETURN_CMSGTFB;
		}

		OutsidePerson outsidePerson;
		String formerName = "", msg = "";
		int isCreate;
		HashMap returnContent;
		HashMap returnPerson;

		//创建或更新台外人员
		outsidePerson = sub_insertOrUpdateOutsidePerson(str_outPhNum, str_outName);
		formerName = outsidePerson.getFormerName();

		returnContent = new HashMap();
		returnPerson = new HashMap();
		if (StringUtils.isNotEmpty(formerName)) {        //存在数据了
			if (StringUtils.equals(formerName, str_outName) == false) {               //用户存在 但是需要更新姓名
				msg = "手机号码:" + str_outPhNum + "已将人员姓名由" + formerName
						+ "改为:" + str_outName;
				isCreate = 1;
			} else {                                                                                       //用户存在 但是传入的姓名和以前的一样 所以不需要更新
				msg = "用户已找到";
				isCreate = 0;
			}
		} else {
			msg = "用户新建成功";
			isCreate = 0;
		}

		returnPerson.put("zPerno", outsidePerson.getZPerno());
		returnPerson.put("zPerna", outsidePerson.getZPerna());
		returnPerson.put("zMobph", outsidePerson.getZMobph());
		returnPerson.put("zGroupNm", " - ");

		returnContent.put("message", msg);
		returnContent.put("isCreate", isCreate);
		returnContent.put("person", returnPerson);
		setTFBContent(SUCCESS, returnContent);
		return RETURN_CMSGTFB;
	}

	/**
	 * 添加台外人员进入群组
	 * 先按手机号进行查询，如果不存在 就新建 ，如果存在的话 再检查名字是否有改动 有改动就更新
	 * 然后检查这个人在不在组内 如果在组内 检查是不是名字改变了，不在组内就插入进组
	 *
	 * @return
	 */
	public String appendOutsideToGroup() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_groupID = request.getParameter("groupID");
		String str_outName = request.getParameter("outName");
		String str_outPhNum = request.getParameter("outPhoneNumber");

		int appendTFB;
		OutsidePerson outsidePerson;
		String formerName;

		logger.debug(str_groupID);
		logger.debug(str_outName);
		logger.debug(str_outPhNum);

		if (StringUtils.isEmpty(str_groupID)) {
			setTFBContent(ERROR, "群组Id不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_outName)) {
			setTFBContent(ERROR, "人员姓名不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_outPhNum)) {
			setTFBContent(ERROR, "人员手机号不能为空");
			return RETURN_CMSGTFB;
		} else if (CommonFunc.isMobileValid(str_outPhNum) == false) {
			setTFBContent(ERROR, "手机号格式不正确");
			return RETURN_CMSGTFB;
		}

		//创建或更新台外人员
		outsidePerson = sub_insertOrUpdateOutsidePerson(str_outPhNum, str_outName);
		formerName = outsidePerson.getFormerName();

		//将人员插入组
		appendTFB = sub_appendPersonToGroup(str_groupID, str_outPhNum);      //人员手机号 就是他的ID
		if (appendTFB == -1) {      //setTFBContent(ALERT, "用户已经在群组中。");
			//人员ID(手机号)已经在这个群组中了
			// 如果名字改变了，则只需要更新前台界面的名字
			if (StringUtils.isNotEmpty(formerName) && (StringUtils.equals(formerName, str_outName) == false)) {
				HashMap returnContent = new HashMap();
				HashMap returnPerson = new HashMap();
				String msg = "手机号码:" + str_outPhNum + "已经在群组中|br|已将人员姓名由" + formerName
						+ "改为:" + str_outName;

				returnPerson.put("zPerno", outsidePerson.getZPerno());
				returnPerson.put("zPerna", outsidePerson.getZPerna());

				returnContent.put("message", msg);
				returnContent.put("update", "1");
				returnContent.put("person", returnPerson);
				setTFBContent(ALERT, returnContent);
			}
		}
		return RETURN_CMSGTFB;
	}

	/**
	 * 根据手机号和姓名 创建台外人员
	 * 先按手机号进行查询，如果不存在 就新建 ，如果存在的话 再检查名字是否有改动 有改动就更新
	 *
	 * @param outPhNum
	 * @param outName
	 * @return
	 */
	private OutsidePerson sub_insertOrUpdateOutsidePerson(String outPhNum, String outName) {
		OutsidePerson returnPerson;
		String str_formerName = "";

		//TODO 还应该判断该手机号是否是台内人员

		//台外人员 将手机号作为主键(userID) 存入person表
		// 如果存在就更新，否则就新建
		Person outStaff = customMsgService.getPersonInfo(outPhNum);
		if (outStaff == null) {     //还没有该手机号的记录，进行新建person
			outStaff = new Person();
			outStaff.setZPerno(outPhNum);              //台外人员的工作证号 就是 手机号
			outStaff.setZMobph(outPhNum);
			outStaff.setZPerna(outName);
			outStaff.setZType("1");                                   //1是群组添加的台外人员
			outStaff.setZCrdat(new Timestamp(GregorianCalendar.getInstance().getTimeInMillis()));     //创建时间

			smsService.insertPerson(outStaff);
		} else {      //该手机号已经有记录了， 进行更新person
			str_formerName = outStaff.getZPerna();                     //记录一下上次的姓名
			outStaff.setZPerna(outName);                    //NOTE:没有改拼音
			outStaff.setZType("1");                                   //1是群组添加的台外人员

			if (StringUtils.equals(str_formerName, outName) == false) {               //名字不一样的 才更新
				smsService.updatePerson(outStaff);
			}
		}      //人员是否存在判断完毕


		//根据person新建OutsidePerson
		returnPerson = new OutsidePerson(outStaff);
		//给曾用名赋值
		returnPerson.setFormerName(str_formerName);

		return returnPerson;
	}

	/**
	 * 将用户插入某一群组中
	 *
	 * @return
	 */
	public String appendStaffToGroup() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_staffID = request.getParameter("staffID");
		String str_groupID = request.getParameter("groupID");

		logger.debug(str_staffID);
		logger.debug(str_groupID);

		//判断是不是为空
		if (StringUtils.isEmpty(str_staffID)) {
			setTFBContent(ERROR, "人员Id不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_groupID)) {
			setTFBContent(ERROR, "群组d不能为空");
			return RETURN_CMSGTFB;
		}
		//TODO 还应该检查该人员是否为台内人员
		//将人员插入组
		sub_appendPersonToGroup(str_groupID, str_staffID);

		return RETURN_CMSGTFB;
	}

	/**
	 * 将用户插入某一群组中
	 *
	 * @param groupID
	 * @param staffID
	 * @return
	 */
	private int sub_appendPersonToGroup(String groupID, String staffID) {
		Map returnMap = null;
		//如果已经在组里了 就不继续插入了
		CmsgGroupSub cmsgGroupSub = customMsgService.getCmsgGroupSub(groupID, staffID);
		if (cmsgGroupSub != null) {
			setTFBContent(ALERT, "用户已经在群组中。");
			return -1;           //用户已经在群组中
		}
		//不存在 就插入进去   成功插入之后，再查人员的名称
		cmsgGroupSub = customMsgService.insertCmsgGroupSub(groupID, staffID);
		if (cmsgGroupSub != null) {
			try {
				returnMap = CommonFunc.convertBean(cmsgGroupSub);
			} catch (InvocationTargetException e) {
				//				e.printStackTrace();
				setTFBContent(ERROR, "转换错误，请联系系统管理员。");
				return 0;         //失败
			} catch (IntrospectionException e) {
				//				e.printStackTrace();
				setTFBContent(ERROR, "转换错误，请联系系统管理员。");
				return 0;        //失败

			} catch (IllegalAccessException e) {
				//				e.printStackTrace();
				setTFBContent(ERROR, "转换错误，请联系系统管理员。");
				return 0;        //失败
			}
			Person person = customMsgService.getPersonInfo(cmsgGroupSub.getUserId());
			returnMap.put("zPerna", person.getZPerna());
			returnMap.put("zMobph", person.getZMobph());

			setTFBContent(SUCCESS, returnMap);
			return 1;            //成功
		} else {
			setTFBContent(ERROR, "插入错误，请稍后再试。");
			return 0;          //失败
		}
	}

	/**
	 * 将人员从某群组中删除
	 *
	 * @return
	 */
	public String deleteMemberFormGroup() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String[] str_memberIDList = request.getParameterValues("memberIDList[]");
		int effectRowCount = 0;
		List<CmsgGroupSub> memberIDList;

		logger.debug("Action:deleteMemberFormGroup" + str_memberIDList);
		//判断是不是为空
		if (str_memberIDList == null) {
			setTFBContent(ERROR, "成员Id不能为空");
			return RETURN_CMSGTFB;
		}
		memberIDList = new ArrayList<CmsgGroupSub>();
		for (String memberID : str_memberIDList) {
			if (StringUtils.isNotEmpty(memberID)) {
				CmsgGroupSub cmsgGroupSub = new CmsgGroupSub();
				cmsgGroupSub.setId(Long.parseLong(memberID));
				memberIDList.add(cmsgGroupSub);
			}
		}
		effectRowCount = customMsgService.doDeleteMemberFromGroup(memberIDList);
		if (effectRowCount > 0) {
			setTFBContent(SUCCESS, effectRowCount);
		} else {
			setTFBContent(ERROR, effectRowCount);
		}

		return RETURN_CMSGTFB;
	}

	/**
	 * 根据组号 获取该群组下的人员
	 *
	 * @return
	 */
	public String getGroupMemberList() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_userID = request.getParameter("userID");
		String str_groupID = request.getParameter("groupID");
		int effectRowCount = 0;
		logger.debug(str_userID);
		logger.debug(str_groupID);
		//判断是不是为空
		if (StringUtils.isEmpty(str_userID)) {
			setTFBContent(ERROR, "用户ID不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_groupID)) {
			setTFBContent(ERROR, "群组Id不能为空");
			return RETURN_CMSGTFB;
		}

		groupMemberTDataJson = customMsgService.getGpMemberTableData(str_groupID);
		return "gpMemberList";
	}

	//=======groupMember========   end
	//=======my_group========   start

	/**
	 * 根据组号 更新组名称
	 *
	 * @return
	 */
	public String updateGroup() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_userID = request.getParameter("userID");
		String str_groupID = request.getParameter("groupID");
		String str_groupName = request.getParameter("groupName");
		int effectRowCount = 0;
		logger.debug(str_userID);
		logger.debug(str_groupID);
		logger.debug(str_groupName);
		//判断是不是为空
		if (StringUtils.isEmpty(str_groupName)) {
			setTFBContent(ERROR, "用户ID不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_groupID)) {
			setTFBContent(ERROR, "群组Id不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_groupName)) {
			setTFBContent(ERROR, "群组名称不能为空");
			return RETURN_CMSGTFB;
		}

		effectRowCount = customMsgService.doUpdateGroupName(Long.parseLong(str_groupID), str_groupName);
		if (effectRowCount > 0) {
			setTFBContent(SUCCESS, effectRowCount);
		} else {
			setTFBContent(ERROR, effectRowCount);
		}
		return RETURN_CMSGTFB;
	}

	/**
	 * 删除群组   (只更新状态)
	 *
	 * @return
	 */
	public String deleteGroup() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_userID = request.getParameter("userID");
		String str_groupID = request.getParameter("groupID");
		int effectRowCount;
		logger.debug(str_userID);
		logger.debug(str_groupID);
		//判断是不是为空
		if (StringUtils.isEmpty(str_userID)) {
			setTFBContent(ERROR, "用户ID不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_groupID)) {
			setTFBContent(ERROR, "群组Id不能为空");
			return RETURN_CMSGTFB;
		}

		effectRowCount = customMsgService.doDeleteGroup(Long.parseLong(str_groupID));
		if (effectRowCount > 0) {
			setTFBContent(SUCCESS, effectRowCount);
		} else {
			setTFBContent(ERROR, effectRowCount);
		}

		return RETURN_CMSGTFB;
	}

	/**
	 * 创建新的群组 并记录创建人
	 *
	 * @return
	 */
	public String createGroup() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_userID = request.getParameter("userID");
		String str_groupName = request.getParameter("groupName");

		logger.debug(str_userID);
		logger.debug(str_groupName);
		//判断是不是为空
		if (StringUtils.isEmpty(str_userID)) {
			setTFBContent(ERROR, "用户ID不能为空");
			return RETURN_CMSGTFB;
		} else if (StringUtils.isEmpty(str_groupName)) {
			setTFBContent(ERROR, "群组名称不能为空");
			return RETURN_CMSGTFB;
		}

		CmsgGroup cmsgGroup = customMsgService.doCreateGroup(str_userID, str_groupName);
		setTFBContent(SUCCESS, cmsgGroup);
		return RETURN_CMSGTFB;
	}

	/**
	 * 根据用户ID 找到用户所建立的群组
	 *
	 * @return
	 */
	public String getMyGroup() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String str_userID = request.getParameter("userID");

		logger.debug(str_userID);
		//判断是不是为空
		if (StringUtils.isEmpty(str_userID)) {
			setTFBContent(ERROR, "用户ID不能为空");
			return RETURN_CMSGTFB;
		}

		myGroupTDataJson = customMsgService.getMyGroupTableData(str_userID);
		return "myGroupList";
	}
	//=======my_group========   end

	/**
	 * 设置返回的TFB的json
	 *
	 * @param state
	 * @param content
	 */
	private void setTFBContent(char state, Object content) {
		TFBJson = new HashMap();
		TFBJson.put("success", state);
		TFBJson.put("content", content);
	}

	public HashMap getTFBJson() {
		return TFBJson;
	}

	public void setTFBJson(HashMap TFBJson) {
		this.TFBJson = TFBJson;
	}

	public HashMap getMyGroupTDataJson() {
		return myGroupTDataJson;
	}

	public void setMyGroupTDataJson(HashMap myGroupTDataJson) {
		this.myGroupTDataJson = myGroupTDataJson;
	}

	public HashMap getGroupMemberTDataJson() {
		return groupMemberTDataJson;
	}

	public void setGroupMemberTDataJson(HashMap groupMemberTDataJson) {
		this.groupMemberTDataJson = groupMemberTDataJson;
	}

	public HashMap getStaffTDataJson() {
		return staffTDataJson;
	}

	public void setStaffTDataJson(HashMap staffTDataJson) {
		this.staffTDataJson = staffTDataJson;
	}

	public HashMap getRetrievePersonTDataJson() {
		return retrievePersonTDataJson;
	}

	public void setRetrievePersonTDataJson(HashMap retrievePersonTDataJson) {
		this.retrievePersonTDataJson = retrievePersonTDataJson;
	}

	public HashMap getAddedOutPersonJson() {
		return addedOutPersonJson;
	}

	public void setAddedOutPersonJson(HashMap addedOutPersonJson) {
		this.addedOutPersonJson = addedOutPersonJson;
	}

	public HashMap getTextListJson() {
		return textListJson;
	}

	public void setTextListJson(HashMap textListJson) {
		this.textListJson = textListJson;
	}

	public HashMap getMeetingListJson() {
		return meetingListJson;
	}

	public void setMeetingListJson(HashMap meetingListJson) {
		this.meetingListJson = meetingListJson;
	}
}
